
let fs = require('fs');

var nodeCrypto = require('crypto'),
    algorithm = 'aes-256-ctr',
    encrykey = 'flashme.cn'; // 密钥

function encrypt(text) {
    var cipher = nodeCrypto.createCipher(algorithm, encrykey)
    var crypted = cipher.update(text, 'utf8', 'hex')
    crypted += cipher.final('hex');
    return crypted;
}

function decrypt(text) {
    try {
        var decipher = nodeCrypto.createDecipher(algorithm, encrykey)
        var dec = decipher.update(text, 'hex', 'utf8')
        dec += decipher.final('utf8');
        return dec;
    }catch(err){
        return '非hex字符串'
    }
    
}

//解密
fs.readFile('./source2.txt', 'utf8', function (err, data) {
    if (!err) {
        var dec = decrypt(data);
        console.log('解密结果：', dec);
        fs.writeFileSync('./crypto-de.txt', dec);
    } else {
        console.log('缺失 source2.txt 加密文件');
    }
})

//加密
fs.readFile('./source.txt', 'utf8', function (err, data) {
    if (!err) {
        var enc = encrypt(data)
        console.log('加密结果：', enc);
        fs.writeFileSync('./crypto-en.txt', enc);
    } else {
        console.log('缺失 source.txt 明文文件');
    }
})